<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>woodwhales-code-generator</title>
<link rel="stylesheet" th:href="@{/webjars/layui/css/layui.css}" media="all">
<link rel="stylesheet" th:href="@{/code-generator/my-css/mycss.css}" >
</head>
<body>
<div class="layui-container">
<div th:replace="~{code-generator/my-common/common::header}"></div>

<div class="layui-row">
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
  <legend>数据库链接信息</legend>
</fieldset>
<form class="layui-form">
  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label">数据库类型</label>
      <div class="layui-input-block">
        <input type="radio" name="dbType" lay-filter="dbType-filter" value="MYSQL" id="MYSQL" title="MySQL" checked="">
        <input type="radio" name="dbType" lay-filter="dbType-filter" value="ORACLE" id="ORACLE" title="Oracle">
        <input type="radio" name="dbType" lay-filter="dbType-filter" value="PGSQL" id="PGSQL" title="PostgreSQL">
        <input type="text" name="driverClassName" id="driverClassName" style="display: none" autocomplete="off" class="layui-input" value="com.mysql.cj.jdbc.Driver">
      </div>
    </div>
    <div class="layui-inline">
      <label class="layui-form-label">生成代码</label>
      <div class="layui-input-block">
        <input type="checkbox" name="generateCode" checked="" id="generateCode" lay-skin="switch" lay-text="是|否">
      </div>
    </div>
    <div class="layui-inline">
      <label class="layui-form-label">覆盖代码</label>
      <div class="layui-input-block">
        <input type="checkbox" name="overCode" checked="" id="overCode" lay-skin="switch" lay-text="是|否">
      </div>
    </div>
    <div class="layui-inline">
      <label class="layui-form-label">覆盖文档</label>
      <div class="layui-input-block">
        <input type="checkbox" name="overMarkdown" checked="" id="overMarkdown" lay-skin="switch" lay-text="是|否">
      </div>
    </div>
  </div>
  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label">生成配置</label>
    </div>
    <div class="layui-inline">
      <label class="layui-form-label">markdown</label>
      <div class="layui-input-block">
        <input type="checkbox" name="generateMarkdown" id="generateMarkdown" lay-skin="switch" lay-text="是|否">
      </div>
    </div>
    <div class="layui-inline">
      <label class="layui-form-label">controller</label>
      <div class="layui-input-block">
        <input type="checkbox" name="generateController" id="generateController" lay-skin="switch" lay-text="是|否">
      </div>
    </div>
    <div class="layui-inline">
      <label class="layui-form-label">service</label>
      <div class="layui-input-block">
        <input type="checkbox" name="generateService" id="generateService" lay-skin="switch" lay-text="是|否">
      </div>
    </div>
    <div class="layui-inline">
      <label class="layui-form-label">batchMapper</label>
      <div class="layui-input-block">
        <input type="checkbox" name="generateBatchMapper" id="generateBatchMapper" lay-skin="switch" checked="" lay-text="是|否">
      </div>
    </div>
  </div>
  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label">IP地址</label>
      <div class="layui-input-inline">
        <input type="text" name="ip" id="ip" lay-verify="required" autocomplete="off" placeholder="请输入主机名或IP地址" class="layui-input" value="127.0.0.1">
      </div>
    </div>
    <div class="layui-inline">
      <label class="layui-form-label">端口</label>
      <div class="layui-input-inline">
        <input type="text" name="port" id="port" lay-verify="required" autocomplete="off" class="layui-input" placeholder="请输入端口号" value="3306">
      </div>
    </div>
    <div class="layui-inline" id="sidDivId" style="display: none">
      <label class="layui-form-label">SID</label>
      <div class="layui-input-inline">
        <input type="text" name="sid" id="sid" lay-verify="required" autocomplete="off" placeholder="请输入SID" class="layui-input" value="orcl">
      </div>
    </div>
  </div>
  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label">用户</label>
      <div class="layui-input-inline">
        <input type="text" name="username" id="username" lay-verify="required" autocomplete="off" placeholder="请输入用户名" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
      <label class="layui-form-label">密码</label>
      <div class="layui-input-inline">
        <input type="password" name="password" id="password" lay-verify="required|pass" placeholder="请输入密码" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
      <div class="layui-btn-group">
        <button type="button" id="saveConfigBtn" class="layui-btn layui-bg-green layui-btn-sm">
          保存配置
        </button>
        <button type="button" id="loadConfigBtn" class="layui-btn layui-bg-cyan layui-btn-sm">
          加载配置
        </button>
      </div>
    </div>
  </div>
  <div class="layui-form-item" id="schemaDivId" hidden="true">
    <div class="layui-inline">
      <label class="layui-form-label">schema</label>
      <div class="layui-input-inline">
        <select name="schema" id="schema" lay-filter="schema" disabled="">
          <option value=""></option>
        </select>
      </div>
    </div>
      <div class="layui-inline">
        <label class="layui-form-label">数据库版本</label>
        <div class="layui-input-inline">
          <div class="layui-form-mid layui-word-aux" id="dbVersion"></div>
        </div>
      </div>
  </div>
  <div class="layui-form-item" id="pageNameAndPathId" hidden="true">
    <div class="layui-inline">
      <label class="layui-form-label">目录</label>
      <div class="layui-input-inline">
        <input type="text" name="generateDir" id="generateDir" autocomplete="off" placeholder="请指定要生成的目录路径" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
      <label class="layui-form-label">包名</label>
      <div class="layui-input-inline">
        <input type="text" name="packageName" id="packageName" autocomplete="off" placeholder="请输入要生成的包名称" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
      <label class="layui-form-label">作者</label>
      <div class="layui-input-inline">
        <input type="text" name="author" id="author" autocomplete="off" placeholder="请输入作者名称" class="layui-input">
      </div>
    </div>
  </div>
  <div class="layui-form-item" id="ormId" hidden="true">
    <label class="layui-form-label">ORM框架</label>
    <div class="layui-input-block">
      <input type="radio" name="orm" id="myBatis" value="myBatis" title="MyBatis">
      <input type="radio" name="orm" id="myBatisPlus" value="myBatisPlus" title="MyBatisPlus">
    </div>
  </div>
  <div class="layui-form-item" id="superClassDivId" hidden="true">
    <label class="layui-form-label">父类</label>
    <div class="layui-input-inline">
      <input type="text" name="superClass" id="superClass" autocomplete="off" placeholder="请输入父类" class="layui-input">
    </div>
  </div>
  <div class="layui-form-item" id="interfaceDivId" hidden="true">
    <label class="layui-form-label">接口</label>
    <div class="layui-input-block">
      <div class="layui-col-md1"><button class="layui-btn layui-btn-fluid" id="addInterface">添加</button></div>
      <div class="layui-col-md1"><button class="layui-btn layui-btn-fluid layui-bg-red" id="clearInterface">清空</button></div>
      <div class="layui-col-md10" id="interfaceListDivId"></div>
    </div>
  </div>
  <div class="layui-form-item">
      <div class="layui-row layui-col-space15">
        <div class="layui-col-md6">
          <button type="submit" class="layui-btn layui-btn-fluid" lay-submit="" id="btnId" lay-filter="btnId">测试</button>
        </div>
        <div class="layui-col-md6">
          <button class="layui-btn layui-btn-primary layui-btn-fluid" id="resetBtnId">重置</button>
        </div>
      </div>
  </div>
</form>
</div>

<div class="layui-row" id="tableInfosDiv" hidden="true">
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;" id="tableInfoLabelId" hidden="true">
  <legend>数据库表展示</legend>
</fieldset>

<a class="layui-btn layui-btn-warm layui-btn-fluid" id="addNavigationConfig">添加配置</a>
<table id="tableInfosId" lay-filter="tableInfosId"></table>
</div>

<script type="text/html" id="operationBar">
  <a class="layui-btn layui-btn-xs" href="/addListPageConfig?tableKey={{d.tableKey}}">添加</a>
</script>

<div th:replace="~{code-generator/my-common/common::footer}"></div>
</div>

<script th:src="@{/webjars/layui/layui.js}"></script>
<script th:src="@{/webjars/jquery/jquery.min.js}"></script>
<script th:src="@{/code-generator/my-js/my.js}"></script>
<script type="text/javascript" th:inline="none">

  layui.use(['form', 'layer', 'table', 'layedit', 'util', 'element'], function(){
    var form = layui.form,
            layer = layui.layer,
            util = layui.util,
            element = layer.element,
            table = layui.table;

    form.on('radio(dbType-filter)', function(data){
      if(data.value === 'MYSQL') {
        $('#driverClassName').val('com.mysql.cj.jdbc.Driver');
        $('#port').val(3306);
        sidRemoveAttr();
      } else {
        $('#driverClassName').val('oracle.jdbc.OracleDriver');
        $('#port').val(1521);
        sidAddAttr();
      }
    });

    //自定义验证规则
    form.verify({
      otherReq: function(value, item){
        var $ = layui.$;
        var verifyName=$(item).attr('name')
                , verifyType=$(item).attr('type')
                ,formElem=$(item).parents('.layui-form')//获取当前所在的form元素，如果存在的话
                ,verifyElem=formElem.find('input[name='+verifyName+']')//获取需要校验的元素
                ,isTrue= verifyElem.is(':checked')//是否命中校验
                ,focusElem = verifyElem.next().find('i.layui-icon');//焦点元素
        if(!isTrue || !value){
          //定位焦点
          focusElem.css(verifyType=='radio'?{"color":"#FF5722"}:{"border-color":"#FF5722"});
          //对非输入框设置焦点
          focusElem.first().attr("tabIndex","").css("outline","").blur(function() {
            focusElem.css(verifyType=='radio'?{"color":""}:{"border-color":""});
          }).focus();
          return '必填项不能为空';
        }
      }
    });

	$('#resetBtnId').click(function () {
      $("#generateDir").val('');
      $("#packageName").val('');
      $("#superClass").val('');
      $("#author").val('');

      ["pageNameAndPathId", "interfaceDivId", "superClassDivId", "tableInfosDiv", "schemaDivId", "ormId"].forEach(hideItem);
      ["myBatisPlus", "myBatis", "generateDir", "packageName"].forEach(removeAttr);

      clearInterfaceFun();
      updateBtnToTest();

	  if('测试' === $('#btnId').html()) {
        $("#schema").empty();
        $('#schema').removeAttr("lay-verify");
        $('input[name=orm]').prop('checked', false);
        layui.form.render('radio');
        layui.form.render("select");
	    return false;
      }

	  if('提交' === $('#btnId').html()) {
        $("#username").val('');
        $("#password").val('');
        updateBtnToTest();
        return false;
      }

      return false;
    })

    let interfaceList = new Array();

    window.closeTagInner = function(index) {
      interfaceList.splice(index, 1);
      showTagList(interfaceList);
    }

    function clearInterfaceFun() {
      interfaceList.splice(0, interfaceList.length);
      showTagList(interfaceList);
    }

    $('#saveConfigBtn').click(function () {
      let data = {
        "driverClassName": $("#driverClassName").val(),
        "ip": $("#ip").val(),
        "port": $("#port").val(),
        "sid": $("#sid").val(),
        "username": $("#username").val(),
        "password": $("#password").val(),
        "generateCode": false,
        "overCode": false,
        "overMarkdown": false,
        "generateMarkdown": false,
        "generateController": false,
        "generateService": false,
        "generateBatchMapper": false
      }

      $("input:checkbox[name='generateCode']:checked").each(function(i){
        data.generateCode = $(this).val();
      });
      $("input:checkbox[name='overCode']:checked").each(function(i){
        data.overCode = $(this).val();
      });
      $("input:checkbox[name='overMarkdown']:checked").each(function(i){
        data.overMarkdown = $(this).val();
      });
      $("input:checkbox[name='generateMarkdown']:checked").each(function(i){
        data.generateMarkdown = $(this).val();
      });
      $("input:checkbox[name='generateController']:checked").each(function(i){
        data.generateController = $(this).val();
      });
      $("input:checkbox[name='generateService']:checked").each(function(i){
        data.generateService = $(this).val();
      });
      $("input:checkbox[name='generateBatchMapper']:checked").each(function(i){
        data.generateBatchMapper = $(this).val();
      });
      addConfigData('/dbConfig/add', data);
    });

    $('#loadConfigBtn').click(function() {
      loadConfigData('/dbConfig/page', undefined);
    });

    function loadConfigData(content) {
      layer.open({
        type: 2,
        title: '加载配置',
        area: ['72%', '580px'],
        fixed: true,
        content: content
      });
    }

    function addConfigData(content, data) {
      var lay = layer.open({
        type: 2,
        title: '保存配置',
        area: ['72%', '580px'],
        fixed: true,
        content: content,
        success: function (layero, index) {
          let childBody = layer.getChildFrame('body',index);
          let iframeWin = layero.find('iframe')[0].contentWindow;

          childBody.contents().find("#driverClassName").val(data.driverClassName);

          if(data.driverClassName === 'oracle.jdbc.OracleDriver') {
            childBody.contents().find("#sidDivId").show();
            childBody.contents().find("#sid").val(data.sid);
            childBody.contents().find("#sid").attr('lay-verify','required');
            data.dbType = 'ORACLE';
          }

          if(data.driverClassName === 'com.mysql.cj.jdbc.Driver') {
            childBody.contents().find("#sidDivId").hide();
            childBody.contents().find("#sid").val('');
            childBody.contents().find("#sid").removeAttr("lay-verify");
            data.dbType = 'MYSQL';
          }

          childBody.contents().find("#"+data.dbType).prop("checked","true");

          childBody.find("input[name=dbType]").each(function(i,item){
            if($(item).val() === data.dbType){
              $(item).attr('checked',true);
            } else {
              $(item).attr('checked',false);
            }
          });
          childBody.contents().find("#ip").val(data.ip);
          childBody.contents().find("#port").val(data.port);
          childBody.contents().find("#username").val(data.username);
          childBody.contents().find("#password").val(data.password);
          let dbConfigName = data.dbType + "_" + data.ip + "_" + data.port + "_" + data.username;
          childBody.contents().find("#dbConfigName").val(dbConfigName);

          copyValue(childBody, "generateCode", data.generateCode);
          copyValue(childBody, "overCode", data.overCode);
          copyValue(childBody, "overMarkdown", data.overMarkdown);
          copyValue(childBody, "generateMarkdown", data.generateMarkdown);
          copyValue(childBody, "generateController", data.generateController);
          copyValue(childBody, "generateService", data.generateService);
          copyValue(childBody, "generateBatchMapper", data.generateBatchMapper);
          iframeWin.layui.form.render();
        }
      });

      layer.style(lay, {
        overflow: 'visible',
      });
    }

    function copyValue(childBody, childId, value) {
      if('on' === value) {
        childBody.contents().find("#"+childId).attr("checked", true);
      } else {
        childBody.contents().find("#"+childId).attr("checked", false);
      }
    }

    $('#clearInterface').click(function () {
      clearInterfaceFun();
      return false;
    })

	$('#addInterface').click(function () {
      layer.prompt({title: '接口全类名', formType: 3}, function(text, index) {
        text = text.trim();

        let needAdd = true;
        if(text === '') {
          layer.msg('要添加的接口不允许为空', {icon: 5});
          needAdd = false;
          return false;
        }

        interfaceList.map(interface => {
          if(text === interface) {
            layer.msg('当前接口类已添加', {icon: 5});
            needAdd = false;
            return false;
          }
        });

        if(needAdd) {
          interfaceList.push(text);
          showTagList(interfaceList);
          layer.close(index);
        }
      });
      return false;
    })

    function showTagList(interfaceList) {
      let tempArray = new Array();
      $.each(interfaceList, function(index, item) {
        tempArray.push('<div class="tag-class">'+ item +'&nbsp;<a class="tag-close" onclick=closeTag('+index+')>' +
                '<i class="layui-icon layui-icon-close"></i></a></div>');
      });
      $('#interfaceListDivId').html(tempArray.join(""))
    }

    form.on('submit(btnId)', function(data) {
      let index = layer.load(2);
      replaceSwitchBtnValue(data);
      if('测试' === $('#btnId').html()) {
        $('#schema').attr('disabled','');
        $("#schema").empty();
        $('#schema').removeAttr("lay-verify");
        $('input[name=orm]').prop('checked', false);
        layui.form.render('radio');
        $("#dbVersion").html();
        layui.form.render("select");
        clearInterfaceFun();
        $.ajax({
          url:'/generate/buildConnection',
          type:'post',
          dataType:'json',
          contentType:"application/json",
          async:false,
          cache:false,
          data:JSON.stringify(data.field),
          success:function(res) {
            if(res.code === 0) {
              layer.msg('生成成功', {icon: 1});
              // 更新按钮为提交
              updateBtnToSubmit();

              // 数据库下拉选增加数据库名称并且增加必选校验
              $('#schema').append(new Option('请选择', ''));
              $.each(res.data.schemas, function(index, item) {
                $('#schema').append(new Option(item, item));
              });
              $('#schema').removeAttr("disabled");
              $('#schema').attr('lay-verify','required');
              $('#dbVersion').html(res.data.dbVersion)
              layui.form.render("select");
              ["schemaDivId"].forEach(showItem);
              layer.close(index);
            } else {
              layer.close(index);
              layer.alert(res.msg, {
                icon: 5,
                title:'操作失败'
              });
            }
          },
          error:function(res) {
            layer.close(index);
            layer.alert('网络异常', {
              icon: 5,
              title:'操作失败'
            });
          }
        });
        return false;
      }

      if('提交' === $('#btnId').html()) {
        $.ajax({
          url:'/generate/buildTableInfos',
          type:'post',
          dataType:'json',
          contentType:"application/json",
          async:false,
          cache:false,
          data:JSON.stringify(data.field),
          success:function(res) {
            if(res.code === 0) {
              table.render({
                elem: '#tableInfosId' //指定原始表格元素选择器（推荐id选择器）
                ,cellMinWidth: 80
                ,limit: Number.MAX_VALUE
                ,page: false
                ,cols: [[
                  {type:'checkbox'}
                  ,{field: 'dbName', title: '表名', templet: function (data) {
                      return data.dbName;
                    }}
                  ,{field: 'name', title: '类名'}
                  ,{field: 'comment', title: '注释', width: 400}
                  ,{field: 'keys', title: '主键', width: 80, templet:function(data) {
                      return data.keys.join(',');
                    }}
                  ,{title: '配置', width: 80, toolbar: '#operationBar'}
                ]]
                ,data: res.data.tableInfos
              });

              ["pageNameAndPathId", "tableInfoLabelId", "tableInfosDiv", "ormId", "superClassDivId", "interfaceDivId"].forEach(showItem);


              generateDirAddAttr();
              // 只要选中了生成代码，包名必须选择
              if(data.field.generateCode) {
                packageNameAddAttr();
              }
              myBatisPlusAddAttr();
              myBatisAddAttr();
              updateBtnToGenerate();
              let dataBaseInfoKey = res.data.dataBaseInfoKey;
              $('#addNavigationConfig').attr("href","/addNavigationConfig?dataBaseInfoKey=" + dataBaseInfoKey);
              layer.close(index);
              return false;
            } else {
              ["tableInfoLabelId"].forEach(hideItem)
              layer.close(index);
              layer.alert(res.msg, {
                icon: 5,
                title:'操作失败'
              });
            }
          },
          error:function(res) {
            ["tableInfoLabelId"].forEach(hideItem)
            layer.close(index);
            layer.alert('网络异常', {
              icon: 5,
              title:'操作失败'
            });
          }
        });
        return false;
      }

      if('生成' === $('#btnId').html()) {
        // 判断是否选择要生成的表格数据
        let checkStatus = table.checkStatus('tableInfosId');

        if(checkStatus.data.length === 0) {
          layer.msg('请选择要生成的数据库表', {icon: 5});
          return false;
        }

        let dbNameList = new Array();
        $.each(checkStatus.data,function(index, value) {
          dbNameList.push(value.dbName);
        });

        data.field.superClass = data.field.superClass.trim();
        data.field.dbNameList = dbNameList;
        data.field.selectAll = checkStatus.isAll;
        data.field.interfaceList = interfaceList;

        $.ajax({
          url:'/generate/process',
          type:'post',
          dataType:'json',
          contentType:"application/json",
          async:false,
          cache:false,
          data:JSON.stringify(data.field),
          success:function(res) {
            if(res.code === 0) {
              layer.close(index);
              layer.msg('生成成功', {icon: 1});
            } else {
              layer.close(index);
              layer.alert(res.msg, {
                icon: 5,
                title:'操作失败'
              });
            }
          },
          error:function(res) {
            layer.close(index);
            layer.alert('网络异常', {
              icon: 5,
              title:'操作失败'
            });
          }
        });

        return false;
      }

      return false;
    });

    table.on('row(tableInfosId)', function(obj){
      window.location.href = "/detail?tableKey=" + obj.data.tableKey;
    });

    window.loadDbConfig = function(dbConfigCode) {
      let index = layer.load(2);
      $.ajax({
        url:'/databaseConfig/get',
        type:'post',
        dataType:'json',
        contentType:"application/json",
        async:false,
        cache:false,
        data:JSON.stringify({
          'dbConfigCode' : dbConfigCode
        }),
        success:function(res) {
          if(res.code === 0) {
            layer.close(index);
            layer.msg('加载成功', {icon: 1});
            let data = res.data;

            $('#driverClassName').val(data.databaseDriverClassName);
            $('#ip').val(data.configIp);
            $('#port').val(data.configPort);
            $('#username').val(data.configUsername);
            $('#password').val(data.configPassword);

            if(data.driverClassName === 'oracle.jdbc.OracleDriver') {
              $("#sidDivId").show();
              $("#sid").val(data.configSid);
              $("#sid").attr('lay-verify','required');
            }

            if(data.driverClassName === 'com.mysql.cj.jdbc.Driver') {
              $("#sidDivId").hide();
              $("#sid").val('');
              $("#sid").removeAttr("lay-verify");
            }

            $("input[name=dbType]").each(function(i,item){
              if($(item).val() === data.databaseType){
                $(item).attr('checked',true);
              } else {
                $(item).attr('checked',false);
              }
            });

            $('#generateCode').attr("checked", data.extraCodeDbConfig.generateCode);
            $('#generateMarkdown').attr("checked", data.extraCodeDbConfig.generateMarkdown);
            $('#overCode').attr('checked', data.extraCodeDbConfig.overCode);
            $('#overMarkdown').attr('checked', data.extraCodeDbConfig.overMarkdown);
            $('#generateBatchMapper').attr('checked', data.extraFileDbConfig.generateBatchMapper);
            $('#generateController').attr('checked', data.extraFileDbConfig.generateController);
            $('#generateService').attr('checked', data.extraFileDbConfig.generateService);

            form.render();
          } else {
            layer.close(index);
            layer.alert(res.msg, {
              icon: 5,
              title:'加载失败'
            });
          }
        },
        error:function(res) {
          layer.close(index);
          layer.alert('网络异常', {
            icon: 5,
            title:'操作失败'
          });
        }
      });
    }

});
</script>
</body>
</html>
